﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using AzureToolkit.Domain;
using AzureToolkit.Engine;
using Microsoft.Practices.ServiceLocation;
using System.ComponentModel.Composition.Hosting;

namespace AzureToolkit.Worker
{
    public class WorkerRole : WorkerRoleEntryPoint
    {

        public override void Run()
        {
            var catalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory);


            ServiceLocator.SetLocatorProvider(() =>
            {
                var container = new CompositionContainer(catalog);
                return new MefServiceLocator(container);
            });

            var initializers = ServiceLocator.Current.GetAllInstances<IInitializer>();
            foreach (var initilizer in initializers)
            {
                initilizer.Initialize();
            }

            CloudEngine engine = new CloudEngine();

            engine.WithJobScheduler()
                .ScheduleJob<SampleJob>(c => {
                    c.CronSchedule = "* * * * *";
                })
                .ScheduleRecurrentJob<SampleJob>(c => {
                    c.RunEvery = TimeSpan.FromMinutes(1);
                });

            engine.WithMessageHandler<Command1Message, Command1>(c => {
                c.QueueName = "somequeue";
                c.MaxRetries = 3;
                c.MaxThreads = 5;
            });

            engine.Run();

            base.Run();
        }
    }
}
